#include "HttpRequest.hpp"

#include <iostream>

HttpRequest::HttpRequest()
{
}

HttpRequest::~HttpRequest()
{
}

void HttpRequest::parse_url()
{
    url = boost::urls::url(target());
    for (auto &&i : url.params())
    {
        map_params[i.key] = i.value;
    }
}

std::string HttpRequest::path() const
{
    return url.path();
}

StringMap HttpRequest::params() const
{
    return map_params;
}

std::string HttpRequest::query() const
{
    return url.query();
}

static void str_replace(std::string &str, const char ch, const char replace)
{
    for (auto &&i : str)
    {
        if (i == ch)
            i = replace;
    }
}

static StringMap parse_key_value(std::string str, char amount, char interval)
{
    StringMap map = {};
    if (str.find('=') != str.npos)
    {
        str_replace(str, amount, ' ');
        str_replace(str, interval, ' ');
        auto ios = std::istringstream(str);
        std::string key, value;
        while (ios)
        {
            ios >> key >> value;
            map[key] = value;
        }
    }
    return map;
}

StringMap HttpRequest::parse_query(std::string query) const
{
    return parse_key_value(query, '=', '&');
}

StringMap HttpRequest::parse_cookie(std::string cookie) const
{
    return parse_key_value(cookie, '=', ';');
}

std::string HttpRequest::field(HttpRequest::Field field) const
{
    auto it = find(field);
    if (it != end())
    {
        return it->value();
    }
    return {};
}

std::string HttpRequest::field(std::string field) const
{
    auto it = find(field);
    if (it != end())
    {
        return it->value();
    }
    return {};
}
